<template>
    <div class="wrapper">
        <!-- 头部 -->
        <header class="header">
            <div class="header-content">
                <div class="header-content-left">
                    <h1>AI医生,您可信赖的朋友...</h1>
                </div>
            </div>
        </header>

        <!-- 主要咨询区域 -->
        <div class="ai-container" ref="chatWindowRef">
            <!-- 聊天窗口 -->
            <div class="chat-window">
                <div v-for="(message, index) in messages" :key="index" class="message-item" :class="message.type"
                    :style="message.style">
                    <span class="message-prefix">{{ message.type == "user" ? " 我: " : " AI: " }}</span>
                    <div v-html="formatMessage(message.content.text)"></div>
                </div>
            </div>

            <!-- 输入区域 -->
            <div class="input-area">
                <input v-model="inputContent" type="text" placeholder="请输入您的问题..." class="input-box"
                    @keyup.enter="sendQuestion" />
                <button @click="sendQuestion" class="send-btn">
                    <i class="fa fa-paper-plane"></i> 发送
                </button>
            </div>
        </div>

        <!-- 底部 -->
       
    </div>
</template>

<script>
import { nextTick, reactive, ref, toRefs, onMounted } from 'vue';
import axios from 'axios';

export default {
    setup() {
        const chatWindowRef = ref(null);
        const state = reactive({
            inputContent: '',
            messages: [],
        });

        function sendQuestion() {
            if (state.inputContent.trim() === '') return;
            state.messages.push({ 
            type: 'user', 
            content: { 
            text: state.inputContent 
            } 
        });
        scrollToBottom();

        axios
            .post('/api/askDS', { prompt: state.inputContent })
            .then((response) => {
                const aiText = response.data.choices?.[0]?.text;
                if (aiText) {
                    state.messages.push({ type: 'ai', content: { text: aiText } });
                    scrollToBottom();
                }
            })
            .catch(console.log);
            state.inputContent = '';
        }

        function scrollToBottom() {
            nextTick(() => {
                const lastMessage = document.querySelector('.message-item:last-child');
                lastMessage?.scrollIntoView({ behavior: 'smooth' });
            });
        }

        function formatMessage(text) {
            text = text
                .replace(/\n/g, '<br>')
                .replace(/\n\n/g, '<br><br>')
                .replace(/### (.+)/g, '<h3>$1</h3>')
                .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                .replace(/__(.*?)__/g, '<strong>$1</strong>')
                .replace(/\*(.*?)\*/g, '<em>$1</em>')
                .replace(/_(.*?)_/g, '<em>$1</em>')
                .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>')
                .replace(/!\[(.*?)\]\((.*?)\)/g, '<img src="$2" alt="$1">')
                .replace(/(^\s*-|^\s*\*)(.*?)(?=\n|$)/gm, '<li>$2</li>')
                .replace(/<li>(.*?)<\/li>/g, '<ul>\n$&\n</ul>')
                .replace(/```(.*?)```/gs, '<pre><code>$1</code></pre>')
                .replace(/^>(.*?)$/gm, '<blockquote>$1</blockquote>')
                .replace(/^-{3,}$/gm, '<hr>')
                .replace(/^(\*{3,})$/gm, '<hr>');
            return text;
        }

        return {
            ...toRefs(state),
            sendQuestion,
            scrollToBottom,
            formatMessage
        };
    },
};
</script>

<style scoped>
/* 总容器 */
.wrapper {
    max-width: 400px;
    margin: 0 auto;
    border-radius: 16px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    background-color: #f8f9fa;
}

/* 头部 */
.header {
    background: linear-gradient(135deg, #4a90e2, #66b3ff);
    color: white;
    padding: 10px;
    text-align: center;
    font-size: 1.5rem;
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

/* 主要咨询区域 */
.ai-container {
    padding: 18px;
    display: flex;
    flex-direction: column;
    height: calc(100vh - 180px);
    background: linear-gradient(45deg, #266C9F, #70B0BC);
}

/* 聊天窗口 */
.chat-window {
    flex: 1;
    overflow-y: auto;
    background-color: #ffffff;
    border-radius: 20px;
    /* 加大圆角 */
    padding: 16px;
    margin-bottom: 16px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    margin-top: 5px;
    /* 调整间距 */
    transition: all 0.3s ease;
}

/* 消息项 */
.message-item {
    padding: 12px 16px;
    margin-bottom: 12px;
    border-radius: 12px;
    max-width: 80%;
    word-wrap: break-word;
    animation: messageAppear 0.3s ease-out;
}

.message-item.user {
    background: linear-gradient(135deg, #3498db, #74b9ff);
    color: white;
    margin-left: auto;
    border-bottom-right-radius: 0;
}

.message-item.ai {
    background: #f8f9fa;
    color: #333;
    margin-right: auto;
    border-bottom-left-radius: 0;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 消息前缀 */
.message-prefix {
    font-weight: bold;
    margin-right: 6px;
}

/* 输入区域 */
.input-area {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-top: 20px;
    transition: all 0.3s ease;
}

.input-box {
    flex: 1;
    padding: 12px;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    outline: none;
    transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

.input-box:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
}

.send-btn {
    padding: 12px 24px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 8px;
}

.send-btn:hover {
    background-color: #0056b3;
    transform: scale(1.05);
}

/* 消息出现动画 */
@keyframes messageAppear {
    from {
        opacity: 0;
        transform: translateY(8px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* 自定义滚动条 */
.chat-window::-webkit-scrollbar {
    width: 6px;
}

.chat-window::-webkit-scrollbar-track {
    background-color: #f8f9fa;
}

.chat-window::-webkit-scrollbar-thumb {
    background-color: #99c2ff;
    border-radius: 3px;
}

.chat-window::-webkit-scrollbar-thumb:hover {
    background-color: #66b3ff;
}

/* 响应式设计 */
@media (max-width: 420px) {
    .wrapper {
        border-radius: 0;
        box-shadow: none;
    }

    .ai-container {
        padding: 12px;
        height: calc(100vh - 160px);
    }

    .chat-window {
        border-radius: 12px;
        padding: 12px;
        margin-top: 30px;
    }

    .input-area {
        gap: 8px;
    }

    .send-btn {
        padding: 10px 20px;
    }
}
</style>

<!--  

<template>
    <!-- 主容器 -->
    <div class="wrapper">
        <!-- 头部区域 -->
        <header class="header">
            <div class="header-content">
                <div class="header-content-left">
                    <!-- 主标题 -->
                    <h1>AI医生,您可信赖的朋友...</h1>
                </div>
            </div>
        </header>

        <!-- 主要咨询区域容器 -->
        <div class="ai-container" ref="chatWindowRef">
            <!-- 聊天窗口 -->
            <div class="chat-window">
                <!-- 遍历消息列表，渲染每条消息 -->
                <div v-for="(message, index) in messages" :key="index" class="message-item" :class="message.type"
                    :style="message.style">
                    <!-- 消息前缀（用户或AI标识） -->
                    <span class="message-prefix">{{ message.type == "user" ? " 我: " : " AI: " }}</span>
                    <!-- 消息内容，使用v-html渲染格式化后的HTML -->
                    <div v-html="formatMessage(message.content.text)"></div>
                </div>
            </div>

            <!-- 输入区域 -->
            <div class="input-area">
                <!-- 输入框，绑定inputContent变量，监听回车键 -->
                <input v-model="inputContent" type="text" placeholder="请输入您的问题..." class="input-box"
                    @keyup.enter="sendQuestion" />
                <!-- 发送按钮 -->
                <button @click="sendQuestion" class="send-btn">
                    <i class="fa fa-paper-plane"></i> 发送
                </button>
            </div>
        </div>

        <!-- 底部区域 -->
       
    </div>
</template>

<script>
// 导入Vue相关API
import { nextTick, reactive, ref, toRefs, onMounted } from 'vue';
// 导入axios用于HTTP请求
import axios from 'axios';

export default {
    setup() {
        // 获取聊天窗口DOM引用
        const chatWindowRef = ref(null);
        // 创建响应式状态对象
        const state = reactive({
            inputContent: '', // 输入框内容
            messages: [],   // 消息列表
        });

        // 发送问题函数
        function sendQuestion() {
            // 如果输入为空则返回
            if (state.inputContent.trim() === '') return;
            
            // 将用户消息添加到消息列表
            state.messages.push({ 
                type: 'user', // 消息类型为用户
                content: { 
                    text: state.inputContent // 消息内容
                } 
            });
            // 滚动到底部
            scrollToBottom();

            // 发送请求到后端API
            axios
                .post('/api/askDS', { prompt: state.inputContent })
                .then((response) => {
                    // 获取AI回复文本
                    const aiText = response.data.choices?.[0]?.text;
                    if (aiText) {
                        // 将AI回复添加到消息列表
                        state.messages.push({ type: 'ai', content: { text: aiText } });
                        // 滚动到底部
                        scrollToBottom();
                    }
                })
                .catch(console.log); // 捕获并打印错误
            // 清空输入框
            state.inputContent = '';
        }

        // 滚动到底部函数
        function scrollToBottom() {
            // 在下一个DOM更新周期执行
            nextTick(() => {
                // 获取最后一条消息元素
                const lastMessage = document.querySelector('.message-item:last-child');
                // 平滑滚动到该元素
                lastMessage?.scrollIntoView({ behavior: 'smooth' });
            });
        }

        // 格式化消息文本为HTML
        function formatMessage(text) {
            // 一系列正则替换，将Markdown语法转换为HTML
            text = text
                .replace(/\n/g, '<br>') // 换行符替换为<br>
                .replace(/\n\n/g, '<br><br>') // 双换行替换为双<br>
                .replace(/### (.+)/g, '<h3>$1</h3>') // ###标题替换为<h3>
                .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // **粗体**替换
                .replace(/__(.*?)__/g, '<strong>$1</strong>') // __粗体__替换
                .replace(/\*(.*?)\*/g, '<em>$1</em>') // *斜体*替换
                .replace(/_(.*?)_/g, '<em>$1</em>') // _斜体_替换
                .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>') // 链接替换
                .replace(/!\[(.*?)\]\((.*?)\)/g, '<img src="$2" alt="$1">') // 图片替换
                .replace(/(^\s*-|^\s*\*)(.*?)(?=\n|$)/gm, '<li>$2</li>') // 列表项替换
                .replace(/<li>(.*?)<\/li>/g, '<ul>\n$&\n</ul>') // 列表项包裹<ul>
                .replace(/```(.*?)```/gs, '<pre><code>$1</code></pre>') // 代码块替换
                .replace(/^>(.*?)$/gm, '<blockquote>$1</blockquote>') // 引用替换
                .replace(/^-{3,}$/gm, '<hr>') // 水平线替换
                .replace(/^(\*{3,})$/gm, '<hr>'); // 星号水平线替换
            return text;
        }

        // 返回模板可用的数据和方法
        return {
            ...toRefs(state), // 将响应式状态转换为refs
            sendQuestion,    // 发送问题方法
            scrollToBottom,  // 滚动方法
            formatMessage    // 格式化消息方法
        };
    },
};
</script>



 -->